//
//  WBRefreshControl.swift
//  Weibo
//
//  Created by apple on 15/12/17.
//  Copyright © 2015年 idcast. All rights reserved.
//

import UIKit
///下来刷新控件偏移量
private let WBRefreshControlOffset: CGFloat = -60

class WBRefreshControl: UIRefreshControl {
    
    //MARK: 重写系统的方法
    override func endRefreshing() {
        super.endRefreshing()
        //停止动画
        refreshView.stopAnimation()
    }
    
    ///主动触发开始刷新动画  不会触发监听方法
    override func beginRefreshing() {
    
        super.beginRefreshing()
        
        refreshView.startAnimation()
    }
    
    //MARK: KVO 监听方法
    /**
       1 始终在屏幕上
       2 下拉的时候 fram的y 值一直减小 相反（向上推的时候 一直变大）
       3 默认的y 值为0
    */
    ///箭头旋转标记

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if frame.origin.y > 0 {
     
            return
        }
        //判断是否正在刷新
        if refreshing {
        
            refreshView.startAnimation()
            return
        }
        if frame.origin.y < WBRefreshControlOffset && !refreshView.rotateFlag {
        
            print("反过来")
            refreshView.rotateFlag = true

        }else if frame.origin.y >= WBRefreshControlOffset && refreshView.rotateFlag {
        
            print("转过去")
            refreshView.rotateFlag = false

        }
    }
    
    //MARK: 构造函数
    override init() {
        super.init()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    private func setupUI() {
    
        //添加控件
        addSubview(refreshView)
        
        //自动布局
        refreshView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
            make.size.equalTo(refreshView.bounds.size)
            
        }
        //多线程异步的方法 主队列 当前线程有任务 就不调度队列中的任务执行
        // 让当前运行循环中的所有代码执行完毕后 运行循环结束前 开始监听
        //方法触发会在下一次运行循环开始
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            //KVO监听属性的变化
            self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
        }
    }
    
    //移除监听器
    deinit {
    
        removeObserver(self, forKeyPath: "frame")
    }
    
  //懒加载控件
    private lazy var refreshView = WBRefreshView.refreshView()

}

///刷新试图 负责处理动画
class WBRefreshView: UIView {
    
    ///旋转标记 
    var rotateFlag = false {
    
        didSet{
        
            retateTipIcon()
        }
    }

 
    @IBOutlet weak var loadingIconView: UIImageView!
    @IBOutlet weak var tipView: UIView!
    
    @IBOutlet weak var tipIconView: UIImageView!
    //从XIB加载 试图  创建个类对象
    class func refreshView() -> WBRefreshView {
    
        //使用UINib 加载xib
        let nib = UINib(nibName: "WBRefreshView", bundle: nil)
        
        return nib.instantiateWithOwner(nil, options: nil)[0] as! WBRefreshView
    }
    private func retateTipIcon() {
        var angle = CGFloat(M_PI)
        angle += rotateFlag ? -0.0000001 : 0.00000002
       //旋转动画   顺时针  和 就近原则
        UIView.animateWithDuration(0.5) { () -> Void in
            self.tipIconView.transform = CGAffineTransformRotate(self.tipIconView.transform, CGFloat(angle))
        }
    }
    ///播放加载动画
    private func startAnimation() {
    
        tipView.hidden = true
        //判断动画是否已经被添加
        let key = "transform.rotation"
        
        if loadingIconView.layer.animationForKey(key) != nil {
        
            return
        }
        
        print("加载动画播放")
        
        let anim = CABasicAnimation(keyPath: key)
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        anim.removedOnCompletion = false
        loadingIconView.layer.addAnimation(anim, forKey: key)
        
    }
    ///停止加载动画
    private func stopAnimation() {
    
        tipView.hidden = false
        loadingIconView.layer.removeAllAnimations()
    }
   
}